/**
 * Created by Joe on 2017/11/1 0005.
 */
$(document).ready(function () {
    initFormValidate();

    if ($("input#company-suggest-search") && $("input#company-suggest-search").length > 0) {
        var url = /*[[@{/partner/getAllCompany}]]*/ '/partner/getAllCompany';
        $("#company-suggest-search").bsSuggest('init', {
            /*url: "/rest/sys/getuserlist?keyword=",*/
            effectiveFields: ["companyName", "companyLaw"],
            searchFields: ["companyName"],
            effectiveFieldsAlias: {companyName: "客户公司名称", companyLaw: "联系人"},
            showBtn: true,
            clearable: true,
            url: url,
            idField: "id",
            keyField: "companyName"
        }).on('onDataRequestSuccess', function (e, result) {
            Utils.console_log('onDataRequestSuccess: ', result);
        }).on('onSetSelectValue', function (e, keyword, data) {
            Utils.console_log('onSetSelectValue: ', keyword, data);
            var companyId = keyword.id;
            $("input[name='companyId']").val(companyId);
            var url = /*[[@{/partner/queryAllByCompany}]]*/ '/partner/queryAllByCompany';
            url = url.concat("/").concat(companyId);
            Utils.ajaxSubmit(url, {}, function (data) {
                var company = data.company;
                var json = {
                    sales: company.sales,
                    companyLaw: company.companyLaw,
                    tel: company.tel,
                    reg_Address: company.address
                };
                Utils.fillInputs(json);
                loadingCompanyAddress(data.addressList);
            });

        }).on('onUnsetSelectValue', function () {
            Utils.console_log('onUnsetSelectValue');
        });
    }
    if ($("input#part-suggest-search") && $("input#part-suggest-search").length > 0) {
        var url = /*[[@{/goods/queryGoodsByKeywords?keyword=}]]*/ '/goods/queryGoodsByKeywords?keyword=';
        Utils.console_log("pn-suggest-search", url);
        $("#part-suggest-search").bsSuggest('init', {
            effectiveFields: ["part"],
            searchFields: ["part"],
            effectiveFieldsAlias: {part: "part号码"},
            idField: "id",
            keyField: "part",
            showBtn: true,
            allowNoKeyword: false,
            getDataMethod: "url",
            url: url,
            //请求数据前，对输入关键字作进一步处理方法。注意，应返回字符串
            fnPreprocessKeyword: function (keyword) {
                return keyword;
            }
            /* //url 获取数据时，对数据的处理，作为 fnGetData 的回调函数
             fnProcessData: function (json) {
             var index, len, data = {value: []};
             if (!json || !json.s || json.s.length === 0) {
             return false;
             }
             len = json.s.length;
             for (index = 0; index < len; index++) {
             data.value.push({
             word: json.s[index]
             });
             }
             data.defaults = '';
             //字符串转化为 json 对象
             return data;
             }*/
        }).on('onDataRequestSuccess', function (e, result) {
            Utils.console_log('onDataRequestSuccess: ', result);
        }).on('onSetSelectValue', function (e, keyword, data) {
            Utils.console_log('onSetSelectValue: ', keyword, data);
            var goodsId = keyword.id;
            $("input[name='goodsId']").val(goodsId);
            $("input[name='part']").val(keyword.key);
            Utils.fillInputs(data);
        }).on('onUnsetSelectValue', function () {
            Utils.console_log('onUnsetSelectValue');
        });
    }
    if ($("input#address-suggest-search") && $("input#address-suggest-search").length > 0) {
        var companyId = $("input#company-suggest-search").attr("data-id");
        var url = /*[[@{/partner/queryAllByCompany}]]*/ '/partner/queryAllByCompany';
        if (companyId == '') {
            companyId = 0;
        }
        url = url.concat("/").concat(companyId);
        Utils.ajaxSubmit(url, {}, function (data) {
            loadingCompanyAddress(data);
        });
    }

    $("#save-order-goods").click(function () {
        if ($("#order-detail-form").valid()) {
            var params = $("#order-detail-form").serializeArray();
            addOrderGoodsList(arrayToJson(params));
            // Utils.console_log('params', toJson(params));
        }
    });
    $("#btn-create-order").click(function () {
        if ($("#order-detail-form").valid()) {
            var url = /*[[@{/ordersales/createNewOrder}]]*/ '/ordersales/createNewOrder';
            var params = $("#order-detail-form").serialize();
            Utils.ajaxSubmit(url, params, function (data) {
                if (data.result == "success") {
                    layer.msg('订单创建成功', {time: 3000, icon: 6});
                }
                if (data.result == "fail") {
                    Utils.errorAlert(data.errorMessage);
                }
            });
        }
    });

    $('#DataTables_order_goodslist').DataTable({
        "paging": false,
        "searching": false,
        "info": false,
        "ordering": false,
        "autoWidth": false,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    /** delete by id **/
    $('#DataTables_order_goodslist').on('click', '.btn-detail-delete', function () {
        var $tr = $(this).parents('tr');
        var row = $('#DataTables_order_goodslist').DataTable().row($tr);
        row.remove().draw();
    });
});

function loadingCompanyAddress(dataList) {
    $("#address-suggest-search").bsSuggest("destroy");
    $("#address-suggest-search").bsSuggest('init', {
        /*url: "/rest/sys/getuserlist?keyword=",*/
        effectiveFields: ["preAddress", "address", "companyName", "contact"],
        searchFields: ["companyName"],
        effectiveFieldsAlias: {preAddress: "地址", address: "明细", companyName: "客户公司名称", contact: "联系人"},
        showBtn: true,
        clearable: true,
        data: dataList,
        idField: "id",
        keyField: "companyName"
    }).on('onDataRequestSuccess', function (e, result) {
        Utils.console_log('loadingCompanyAddress onDataRequestSuccess: ', result);
    }).on('onSetSelectValue', function (e, keyword, data) {
        Utils.console_log('loadingCompanyAddress onSetSelectValue: ', keyword, data);
        var addressId = keyword.id;
        $("input[name='addressId']").val(addressId);
        $("input[name='companyName']").val(keyword.companyName);
        var url = /*[[@{/address/getAddressById}]]*/ '/address/getAddressById';
        if (addressId !== '') {
            url = url.concat("/").concat(addressId);
            Utils.ajaxSubmit(url, {}, function (callbackData) {
                if (callbackData.result == "success") {
                    var addressObj = callbackData.content;
                    var json = {
                        contact:  addressObj.contact,
                        contactTel:  addressObj.contactTel,
                        address:   addressObj.preAddress.concat(addressObj.address)
                    };
                    Utils.fillInputs(json);
                    // $("input[name='memo']").attr("text",data.content.memo);
                }
                if (data.result == "fail") {
                    Utils.errorAlert(data.result.errorMessage);
                }
            });
        }
    }).on('onUnsetSelectValue', function () {
        Utils.console_log('loadingCompanyAddress onUnsetSelectValue');
    });
}

/**添加table行*/
function addOrderGoodsList(params) {
    Utils.console_log("addOrderGoodsList params", params)
    var goodsId = params.goodsId,
        goods = goodsId.concat("-").concat(params.num);
    var checkBoxEle = '<input  type="checkbox" name="goodsIds" checked value="' + goods + '">',
        btnRemoveEle = '<a class="btn btn-danger btn-detail-delete">删除</a>';
    $("#DataTables_order_goodslist").dataTable().fnAddData([checkBoxEle, params.part, params.title, params.num, params.price, params.amount, btnRemoveEle]);
}

function initFormValidate() {
    var validator = $("#order-detail-form").validate({
        errorElement: "span",
        errorClass: "error-block",
        focusInvalid: true,
        rules: {
            num: {required: true, maxlength: 15},
            price: {required: true, maxlength: 30},
            contact: {required: true, maxlength: 30},
            contactTel: {required: true, maxlength: 30},
            address: {required: true, maxlength: 200},
        },
        messages: {
            num: {required: "数量必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            price: {required: "价格必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            contact: {required: "价格必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            contactTel: {required: "价格必须输入", maxlength: $.validator.format("长度不能超过{0}")},
            address: {required: "价格必须输入", maxlength: $.validator.format("长度不能超过{0}")},
        }
    });
    $.validator.addMethod('isNumber', function (value, element, params) {
        return this.optional(element) || Utils.isNumber(value);
    }, "格式错误,请输入有效的数字");
}

function arrayToJson(paramArray) {
    var values = {};
    for (var item in paramArray) {
        values[paramArray[item].name] = paramArray[item].value;
    }
    // Utils.console_log("Json", JSON.stringify(values));
    // return JSON.stringify(values);//json字符串
    return values;

}